$(function() {
    var $person = $('.person-account');
    viewTh();
    //打开新增模态框
    $('.btn-add').click(function() {
        // 清空表单内容
        $('.add-modal').find('.input-text').val('');
        // $('.add-modal').find('.input-text').removeAttr('disabled');
        $('.add-modal').find('.input-textarea').val('');
        // $('.add-modal').find('.input-textarea').removeAttr('disabled');
        $('.a-com-dep').val('请选择部门');
        $('.a-industry-type').val('请选择行业类别');
        $('.a-project-type').val('请选择项目类别');
        $('.a-authorized-person').val('请选择项目编制人员');
        $('.a-contract-belong').val('请选择合同归属单位');
        $('.flag-check').removeClass('on_check');

        //填充承接人、承接部门
        $('.a-undertake-person').val($person.html());
        $('.a-undertake-person').data('id', $person.data('id'));
        $('.a-undertake-dep').val($person.data('dep'));
        $('.a-undertake-person').data('dep-id', $person.data('dep-id'));

        //更改确定按钮class
        $('.update-btn').attr("class", "update-btn add-btn btn");

        fadeModal('.add-modal');
    })

    $('.cancel-btn').click(function() {
        $('.add-modal,.mask').fadeOut();
    })

    // 确定新增项目
    $('.add-modal').on("click", '.add-btn', function() {
        loading();
        // console.log(validateData());
        if (validateData() != undefined) {
            //前端数据
            console.log(validateData());
            //-----------------------------------------------
            var options = getBASEPOSTAJAX();
            options.url = "/epi/tender/project";
            options.data = {
                // 项目名称
                projectName: validateData().projectName,
                // 承接人
                undertakePersonId: $person.data('id'),
                // 承接部门
                undertakeDepId: validateData().undertakeDep_id,
                // 完成部门
                finishDepId: validateData().comDep_id,
                // 省
                province: validateData().province,
                provinceId: validateData().provinceId,
                // 市
                city: validateData().city,
                cityId: validateData().cityId,
                // 区
                district: validateData().district,
                // 行业类别
                industryTypeId: validateData().industry_type_id,
                // 项目类别
                projectTypeId: validateData().project_type_id,
                // 合同归属单位
                contractParty: validateData().conBelong,
                //建设单位
                construction: validateData().unit,
                //任务下达日期
                issuedDate: validateData().startDate,
                //要求完成天数
                needDateDeline: validateData().finTime,
                //联系人
                contactor: validateData().cnnPerson,
                //联系方式
                phone: validateData().cnnPerson,
                //项目编制人员
                authorizePersonId: validateData().pecompose_person_id,
                //税号
                taxId: validateData().tax,
                //开户银行
                bankName: validateData().bank,
                //银行账户
                accountNumber: validateData().acount,
                //项目经费
                projectMoney: validateData().money,
                //承接备注
                undertakeRemark: validateData().comment,
                //地址
                address: validateData().address
            };
            console.log(options.data);
            options.success = function(data) {
                loadingHide();
                console.log(data);
                var status = data.STATUS;
                if (status == 500) {
                    setAlert('非法操作！');
                } else if (status == 400) {
                    setAlert('承接失败！');
                } else if (status == 200) {
                    setAlert('承接成功');
                    fadeOut('.add-modal,.mask');
                    viewTh();
                } else {
                    setAlert('系统繁忙，请刷新重试');
                }

            };
            options.error = function() {
                setAlert('系统繁忙，请刷新重试');
            };
            $.ajax(options);
        }
    })

    // 确定修改项目
    $('.add-modal').on("click", '.edit-btn', function() {
        loading();
        // console.log(validateData());
        if (validateData() != undefined) {
            // 前端数据
            console.log(validateData());
            //-----------------------------------------------
            var options = getBASEPUTAJAX();
            var id = $('.add-modal').data("id");
            options.url = "/epi/tender/project";
            options.data = {
                //项目id
                projectId: id,
                // 项目名称
                projectName: validateData().name,
                // 承接人
                undertakePersonId: $person.data('id'),
                // 承接部门
                undertakeDepId: validateData().undertakeDep_id,
                // 完成部门
                finishDepId: validateData().comDep_id,
                // 省
                province: validateData().province,
                // 市
                city: validateData().city,
                // 区
                district: validateData().district,
                // 行业类别
                industryTypeId: validateData().industry_type_id,
                // 项目类别
                projectTypeId: validateData().project_type_id,
                // 合同归属单位
                contractParty: validateData().conBelong,
                //建设单位
                construction: validateData().unit,
                //任务下达日期
                issuedDate: validateData().startDate,
                //要求完成天数
                needDateDeline: validateData().finTime,
                //联系人
                contactor: validateData().cnnPerson,
                //联系方式
                phone: validateData().cnnPerson,
                //项目编制人员
                authorizePersonId: validateData().pecompose_person_id,
                //税号
                taxId: validateData().tax,
                //开户银行
                bankName: validateData().bank,
                //银行账户
                accountNumber: validateData().acount,
                //项目经费
                projectMoney: validateData().money,
                //承接备注
                undertakeRemark: validateData().comment,
                //地址
                address: validateData().address
            };
            console.log(JSON.stringify(options.data));
            options.success = function(data) {
                loadingHide();
                console.log(data);
                var status = data.STATUS;
                if (status == 500) {
                    setAlert('非法操作！');
                } else if (status == 400) {
                    setAlert('修改失败！');
                } else if (status == 200) {
                    setAlert('修改成功');
                    fadeOut('.add-modal,.mask');
                    viewTh();
                } else {
                    setAlert('系统繁忙，请刷新重试');
                }

            };




            options.error = function() {
                setAlert('系统繁忙，请刷新重试');
            };
            $.ajax(options);
        }
    })

    //输入筛选(拼音模糊查找)
    $('.add-modal').on("focus", ".a-authorized-person", function() {
        $(this).val('');
    })
    $('.add-modal').on("keyup keydown focus", ".a-authorized-person", function() {
        var val = $(this).val();
        console.log(val)
        var options = getBASEGETAJAX();
        options.url = "/assets/json/staff2.json";
        // options.data.projectId = id;
        options.success = function(data) {
            console.log(JSON.stringify(data));
            var myTemplate = Handlebars.compile($("#staff-list").html());
            // 存储拼音对象数组
            var pyVal = [];
            // 存储查询结果
            var searchData = [];
            for (var i = 0; i < data.length; i++) {
                var personName = data[i].personName;
                $('.person-name-input').val(personName);
                var py = $('.person-name-input').toPinyin().toLowerCase().replace(/ /g, '');
                pyVal.push({
                    personName: py,
                    personId: data[i].personId
                });
            }
            // 制作查询结果
            var liData = "";
            //是否找到
            var searchFlag = 0;
            for (var k = 0; k < data.length; k++) {
                if (data[k].personName.indexOf(val) != -1 || pyVal[k].personName.indexOf(val) != -1) {
                    liData += '<li>' + data[k].personName + '</li>';
                    searchFlag = 1;
                }
            }
            if (searchFlag == 0) liData = "<无>";
            console.log(liData);
            $('.a-person-list').html(liData);


        };
        options.error = function() {
            setAlert('系统繁忙，请刷新重试');
        };
        $.ajax(options);
        // alert(111)
    })

    /**
     * [查看详情确定]
     */
    $('.i-btn').click(function() {
        $('.info-modal,.mask').fadeOut();
    })

    //打开修改承接信息模态框
    $('.this-table').on('click', '.edit-info', function() {
        //前端数据
        var projectId = $(this).data('id'); //项目id
        $('.add-modal').data("id", projectId);
        //------------------------------------------------
        var options = getBASEGETAJAX();
        options.url = "/tender/project/" + projectId;
        // options.data.projectId = id;
        options.success = function(data) {
            console.log(JSON.stringify(data));
            var myTemplate = Handlebars.compile($("#edit-template").html());
            // console.log(myTemplate(data))
            $('.edit-info-div').html(myTemplate(data));
            //更改确定按钮class
            $('.update-btn').attr("class", "update-btn edit-btn btn");
            $("#sjld").sjld("#shenfen", "#chengshi", "#quyu");
            fadeModal('.add-modal');

        };
        options.error = function() {
            setAlert('系统繁忙，请刷新重试');
        };
        $.ajax(options);
    })


    //打开详情模态框
    $('.this-table').on('click', '.view-info', function() {
        fadeModal('.info-modal');
        //前端数据
        var id = $(this).data('id'); //项目id
        $('.view-modal').data('id', id);
        // //------------------------------------------------
        var options = getBASEGETAJAX();
        options.url = "/epi/finance/" + id;
        options.data.projectid = id;
        options.success = function(data) {
            var myTemplate = Handlebars.compile($("#three-tip-info-template").html());
            $('.three-tip-info').html(myTemplate(data));

            fadeModal('.info-modal');

        };
        options.error = function() {
            setAlert('系统繁忙，请刷新重试');
        };
        $.ajax(options);

    })

    //废弃项目
    $('.this-table').on('click', '.trash-pro', function() {
        setConfirm('确定废弃此项目？', function() {
            //前端数据
            var id = $(this).data(id); //项目id
            //------------------------------------------------
            var options = getBASEDELETEAJAX();
            options.url = "/tender/project/" + id;
            options.success = function(data) {
                console.log(JSON.stringify(data));
                var status = data.status;
                if (status == 500) {
                    setAlert("非法操作");
                } else if (status == 400) {
                    setAlert("废弃失败");
                } else if (status == 200) {
                    setAlert("废弃成功");
                } else {
                    setAlert('系统繁忙，请刷新重试');
                }
            };
            options.error = function() {
                setAlert('系统繁忙，请刷新重试');
            };
            $.ajax(options);

        })
    })

    $('.flag-check').click(function() {
        $(this).toggleClass('on_check');
    })

    // 增加收款条数
    $(document).on('click', '.a-c-row', function() {
        var len = $('.a-c-row').length;

        $(this).parent('.form-control').after('<div class="form-control">' +
            '<span class="input-title">第' + (len + 1) + '笔收款日期：</span>' +
            '<input type="text" value="" class="a-collection-date input-text-short">' +
            '<span class="">金额：</span>' +
            '<input type="text" value="" class="a-collection-money input-text-short"> ' +
            '<span class="input-title">第' + (len + 1) + '笔发票日期：</span>' +
            '<input type="text" value="" class="a- invoices－date input-text-short">' +
            '<span class="">金额：</span>' +
            '<input type="text" value="" class="a-invoices-money input-text-short"> ' +
            '<span class="money-unit">万元</span>' +
            '<input type="button" name="" value="+" class="a-add a-c-row">' +
            '<input type="button" name="" value="-" class="a-remove a-c-remove">' +
            '</div>')
    })

    // 移除收款条数
    $(document).on('click', '.a-remove', function() {
        $(this).parent('.form-control').remove();
        //更新序列号
        updateList($('.a-collection'), 2, '笔收款日期', '笔发票日期');

    })

    //日历
    $(document).on('focus', '.a-contract-date', function() {
        $('.a-contract-date').fdatepicker();
    })
    $(document).on('focus', '.a-start-date', function() {
        $('.a-start-date').fdatepicker();
    })


    //选择行业类别
    $('.add-modal').on('click', '.a-industry-type', function() {
        var options = getBASEGETAJAX();
        var pageNum = 1;
        var records = 30;
        options.url = "/epi/admin/industryType/industryTypes" + '/' + pageNum + '/' + records;
        options.success = function(data) {
            console.log(data);
            var myTemplate = Handlebars.compile($("#industry-list").html());
            console.log(myTemplate(data))
            $('.a-industry-list').html(myTemplate(data));

        };
        options.error = function() {
            setAlert('系统繁忙，请刷新重试');
        };
        $.ajax(options);
    })

    //选择项目类别
    $('.add-modal').on('click', '.a-project-type', function() {
        var options = getBASEGETAJAX();
        var pageNum = 1;
        var records = 30;
        options.url = "/epi/admin/projectType/projectTypes" + '/' + pageNum + '/' + records;
        options.success = function(data) {
            console.log(data);
            var myTemplate = Handlebars.compile($("#project-list").html());
            console.log(myTemplate(data))
            $('.a-project-list').html(myTemplate(data));

        };
        options.error = function() {
            setAlert('系统繁忙，请刷新重试');
        };
        $.ajax(options);
    })

    // 选择部门
    choiseDep($('.add-modal'), '.a-undertake-dep,.a-com-dep');

    // 全选
    $(document).on('click', '.operate-all', function() {
        if (checkStatus == 0) {
            $('.v-body .checked').addClass('on_check');
            checkStatus = 1;
        } else if (checkStatus == 1) {
            $('.v-body .checked').removeClass('on_check');
            checkStatus = 0;
        }
    })

    //单选
    $(document).on('click', '.checked', function() {
        $(this).toggleClass('on_check');
    })

    // 上一页
    $('.upPage').click(function() {
        var crtPageNum = $('.pagelist').data("page-num");
        var ele = $('.pagelist .ele');
        var max = ele.length;
        if (crtPageNum == 1) {
            setAlert('已至第一页')
        } else if (crtPageNum % max == 1) {
            for (var i = 0; i < max; i++) {
                var eleLi = ele.eq(i).text();
                ele.eq(i).text(eleLi - max);
            }
            ele.removeClass('on');
            ele.eq(max - 1).addClass('on');
            $('.pagelist').data('page-num', crtPageNum - 1);
            viewTable(crtPageNum - 1);

        } else {
            ele.removeClass('on');
            ele.eq((crtPageNum - 2) % max).addClass('on');
            $('.pagelist').data('page-num', crtPageNum - 1);
            viewTable(crtPageNum - 1);
        }
    })

    // 下一页
    $('.downPage').click(function() {
        var crtPageNum = parseInt($('.pagelist').data("page-num"));
        var nextNum = crtPageNum + 1;
        console.log(nextNum);
        var ele = $('.pagelist .ele');
        var totalNum = $('.total-page-num').text();
        var max = ele.length;
        if (crtPageNum == totalNum) {
            setAlert('已至最后一页')
        } else if (crtPageNum % max == 0) {
            for (var i = 0; i < max; i++) {
                var eleLi = parseInt(ele.eq(i).text());
                ele.eq(i).text(eleLi + max);
            }
            ele.removeClass('on');
            ele.eq(0).addClass('on');
            $('.pagelist').data('page-num', nextNum);
            viewTable(nextNum);
        } else {
            ele.removeClass('on');
            ele.eq(crtPageNum % max).addClass('on');
            $('.pagelist').data('page-num', nextNum);
            viewTable(nextNum);
        }

    })

    // 跳转页
    $('.go-btn').click(function() {
        var pgNum = parseInt($('.goPage').val());
        var crtPageNum = $('.pagelist').data("page-num");
        var ele = $('.pagelist .ele');
        var max = ele.length;
        var min = parseInt((pgNum - 1) / max) * max + 1;
        if (isNaN(pgNum)) {
            setAlert('请正确输入页码');
        } else if (pgNum > parseInt(totalNum) || pgNum < 1) {
            setAlert('无此页');
        } else {
            for (var i = 0; i < max; i++) {
                ele.eq(i).text(min + i);
            }
            ele.removeClass('on');
            ele.eq((pgNum - 1) % max).addClass('on');
            $('.pagelist').data('page-num', pgNum);
            viewTable(pgNum);
        }
    })

    // 选择页
    $('.this-table').on('click','.ele',function(){
        var pgNum = parseInt($(this).text());
        var crtPageNum = $('.pagelist').data("page-num");
        var ele = $('.pagelist .ele');
        var max = ele.length;
        ele.removeClass('on');
        ele.eq((pgNum - 1) % max).addClass('on');
        $('.pagelist').data('page-num', pgNum);
        viewTable(pgNum);

    })


})

/**
 * [viewTh 显示表头]
 */
function viewTh() {
    //前端数据
    var modelName = "承接项目";
    //------------------------------------------------
    var options = getBASEGETAJAX();
    options.url = "epi/admin/view/columns/1";
    options.data.modelName = modelName;
    options.success = function(data) {
        console.log(data);
        var myTemplate = Handlebars.compile($("#th-template").html());
        console.log(myTemplate(data))
        $('.v-thead').html(myTemplate(data));
        viewTable();

    };
    options.error = function() {
        setAlert('系统繁忙，请刷新重试');
    };
    $.ajax(options);
}

/**
 * [viewTable 显示表格]
 * @param  {[Float]} pageNum [页码]
 * @param  {[Float]} records [每页记录数]
 */
function viewTable(pageNum, records) {
    //前端数据
    if (records == undefined) {
        records = 20;
    }
    if (pageNum == undefined) {
        pageNum = 1;
    }
    pageSum('financeview', records,function(){
        viewPageList();
    });
    pageCrt();
    var $viewTh = $('.view-th');
    var keyArr = []; //键名数组
    console.log($viewTh.length)
    for (var i = 0; i < $viewTh.length; i++) {
        keyArr.push($viewTh.eq(i).data('key'));
    }
    console.log(keyArr);
    loading();
    //------------------------------------------------
    var options = getBASEGETAJAX();
    options.url = "/epi/finance/projects/" + pageNum + "/" + records;
    options.success = function(data) {
        console.log(data);
        var content = '';
        var k = keyArr[0];

        //遍历数据
        for (var i = 0; i < data.length; i++) {
            content += '<tr>';
            content += '<th class="operate-left"><div class="checked view-check"><input type="checkbox" class="check-input"></div></th>';
            content += '<td>' + (i+1) + '</td>'
            content
            //遍历字段
            for (var j = 0; j < keyArr.length; j++) {
                console.log(keyArr[j])
                if (data[i].hasOwnProperty(keyArr[j])) {

                    if (keyArr[j] == 'receiptSum' || keyArr[j] == 'billSum' || keyArr[j] == 'rewardSum') {
                        console.log('**************************************')
                        if (data[i][keyArr[j]] == data[i].project.projectMoney) {
                            content += '<td class="green">' + data[i][keyArr[j]] + '</td>';
                        } else {
                            content += '<td class="red">' + data[i][keyArr[j]] + '</td>';
                        }
                    } else {
                        console.log('-------------------------------------')
                        content += '<td>' + data[i][keyArr[j]] + '</td>';
                    }
                } else {
                    content += '<td>' + data[i].project[keyArr[j]] + '</td>';
                }

            }
            content += '<th class="operate">' +
                '<button class="drop-left view-info" data-id="' + data[i].project.proid + '">查看详情</button>' +
                
                '</th>';
            content += '</tr>';
        }
        $('.v-body').html(content);
        loadingHide();

    };
    options.error = function() {
        setAlert('系统繁忙，请刷新重试');
    };
    $.ajax(options);

}

function validateData() {
    //承接人、承接部门、任务单编号填写时不用填写，但查看详情时需要
    //G:要传的数据 Y:要验证的数据
    //项目名称、 
    //完成部门、项目编制人员、所属地区、行业类别、
    //项目类别、合同归属、合同日期、任务下达日期、要求完成天数、建设单位不为空
    var basicInfo = {
            projectName: $('.a-name').val(), //项目名称GY
            undertakeDep: $('.a-undertake-dep').val(), //承接部门
            undertakeDep_id: $('.a-undertake-dep').data('id'), //承接部门idG
            comDep: $('.a-com-dep').val(), //完成部门Y
            comDep_id: $('.a-com-dep').data('id'), //完成部门idG
            province: $('#sfdq_tj').val(), //省份
            provinceId: $('#sfdq_num').val(),
            city: $('#csdq_tj').val(), //cheng s
            cityId: $('#csdq_num').val(),
            district: $('#qydq_tj').val(),
            industryType: $('.a-industry-type').val(), //行业类别Y
            industry_type_id: $('.a-industry-type').data('id'), //行业类别idG
            proType: $('.a-project-type').val(), //项目类别Y
            project_type_id: $('.a-project-type').data('id'), //项目类别idG
            conBelong: $('.a-contract-belong').val(), //合同归属单位GY
            conDate: $('.a-contract-date').val(), //合同日期GY
            unit: $('.a-unit').val(), //建设单位GY
            startDate: $('.a-start-date').val(), //任务下达日期GY
            finTime: $('.a-finish-time').val(), //要求完成天数GY
            cnnPerson: $('.a-connect-person').val(), //联系人G
            phone: $('.a-phone').val(), //联系方式G
            pecompose_person: $('.a-authorized-person').val(), //项目编制人员Y
            pecompose_person_id: $('.a-authorized-person').data('id'), //项目编制人员idG
            tax: $('.a-tax').val(), //税号G
            bank: $('.a-bank').val(), //开户银行G
            acount: $('.a-acount').val(), //银行账户G
            money: $('.a-money').val(), //项目经费G
            comment: $('.a-u-note').val(), //承接备注G
            address: $('.a-u-address').val(), //地址G
            tasklist: $('.a-tasklist').val() //任务单编号
        }
        // console.log(basicInfo);
    if (basicInfo.projectName == '') {
        setAlert('请输入项目名称');
    } else if (basicInfo.projectName.length > 255) {
        setAlert('项目名称不得超过255个字');
    } else if (basicInfo.comDep_id == '' || typeof(basicInfo.comDep_id) == "undefined") {
        setAlert('请选择完成部门');
    } else if (basicInfo.industry_type_id == '' || typeof(basicInfo.industry_type_id) == "undefined") {
        setAlert('请选择行业类别');
    } else if (basicInfo.project_type_id == '' || typeof(basicInfo.project_type_id) == "undefined") {
        setAlert('请选择项目类别');
    } else if (basicInfo.conBelong == '') {
        setAlert('请填写合同归属单位');
    } else if (basicInfo.conBelong.length > 255) {
        setAlert('合同归属单位不得超过255个字');
    } else if (basicInfo.conDate == '') {
        setAlert('请设置合同日期');
    } else if (basicInfo.unit == '') {
        setAlert('请输入建设单位');
    } else if (basicInfo.unit.length > 255) {
        setAlert('建设单位不得超过255个字');
    } else if (basicInfo.startDate == '') {
        setAlert('请设置任务下达日期');
    } else if (basicInfo.finTime == '') {
        setAlert('请输入要求完成天数');
    } else if (basicInfo.pecompose_person_id == '' || typeof(basicInfo.pecompose_person_id) == "undefined") {
        setAlert('请检查项目编制人员是否选择');
    } else {
        return basicInfo;
    }

}




/**
 * [choiseDep 下拉列表选择部门]
 * @param  {[type]}   eleParent [祖先节点：document或三级以上父层(用于绑定动态事件，尽量避免document)]
 * @param  {[type]}   ele       [所绑定事件的元素]
 * @param  {Function} callback  [回调函数,扩展函数操作，根据需要传]
 */
function choiseDep(eleParent, ele) {
    eleParent.on('click', ele, function() {
        var _self = $(this);
        updateDepartList(_self.next('.a-drop-list'), function() {
            // 单击－展开列表
            $('.a-drop-list-div').on('dblclick', '.depart-li', function() {
                    var dep = $(this).find('.depart-name').text();
                    _self.val(dep);
                    _self.data("id", $(this).data("id"));
                    _self.next('.a-drop-list').slideUp();
                })
                // 双击－选择部门
            $('.a-drop-list-div').on('click', '.depart-li', function() {
                console.log($(this).parent().parent().next('ul>li').html())
                $(this).next('ul').children('li').slideDown();
            })


        });
    })
}

/**
 * 获取总页数
 * @return {[type]} [description]
 */
function pageSum(tableName, pageSize) {
    $.ajax({
        url: "/epi/common/pages",
        type: "GET",
        data: {
            tableName: tableName,
            pageSize: pageSize
        },
        dataType: 'json',
        success: function(data) {
            console.log(data.pageSum)
            totalNum = data.pageSum;
            $('.total-page-num').text(totalNum);
        },
        error: function() {
            console.log('获取总页数失败');
        }
    })
}

function pageCrt() {
    $('.crt-page-num').text($('.pagelist').data("page-num"));
}

function viewPageList() {
    var totalNum = parseInt($('.total-page-num').text());
    var content = '';
    if (totalNum < 8) {
        for (var i = 0; i < totalNum; i++) {
            if (i == 0) {
                content += '<li class="ele on">1</li>';
            } else {
                content += '<li class="ele">' + (i + 1) + '</li>';
            }

        }
        $('.ele-outer').html(content)
    }
}
